/*
 * Copyright [2011] [Ambud Sharma/ODep Monitor]

   Licensed under the Apache License, Version 2.0 (the "License");

   you may not use this file except in compliance with the License.

   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software

   distributed under the License is distributed on an "AS IS" BASIS,

   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

   See the License for the specific language governing permissions and

   limitations under the License.
 */

package edu.uwsp.orion.odepm.main.server;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.rmi.RMISecurityManager;
import java.rmi.registry.LocateRegistry;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Random;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hdfs.server.namenode.DatanodeDescriptor;
import org.apache.hadoop.ipc.RPC;

import edu.uwsp.orion.odepm.main.client.NodeService;
import edu.uwsp.orion.odepm.main.shared.NodeDetails;
import edu.uwsp.orion.odepm.main.shared.NodeMonitorInfo;
import edu.uwsp.orion.odepm.main.shared.RemoteTrackerInfo;
import edu.uwsp.orion.odepm.main.shared.TrackerInfo;
import edu.uwsp.orion.odepm.main.shared.TrackerSystemStats;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class NodeServiceImpl extends RemoteServiceServlet implements NodeService {

	NodeDetails detailLocal;
	static String localIP;
	
	static{
		try {
            Enumeration<NetworkInterface> interfaces=NetworkInterface.getNetworkInterfaces();
            while(interfaces.hasMoreElements()){
                NetworkInterface iface=interfaces.nextElement();
                if(!iface.isLoopback()){
                    String addressString="";
                    List<InterfaceAddress> allIfaceAddresses=iface.getInterfaceAddresses();
                    for(InterfaceAddress ifaceAddress:allIfaceAddresses){
                        InetAddress address=ifaceAddress.getAddress();
                        if(!address.isLoopbackAddress()){
                            addressString=address.getHostAddress();
                        }
                    }
                    localIP=addressString;
                }
            }
        } catch (SocketException ex) {
            ex.printStackTrace();
        }       
	}
	
	@Override
	public NodeDetails getDetails(String ip) {
		NodeDetails details=new NodeDetails();
		details.name=ip;
		TrackerInfo info=null;
		try{			
		   Configuration con=new Configuration();
	       InetSocketAddress addr=new InetSocketAddress(InetAddress.getByName(ip).getHostAddress(), 16000);
	       ip=addr.getAddress().getHostAddress();	       
	       if(ip.startsWith("127") || ip.startsWith("local")){
	    	   addr=new InetSocketAddress(localIP, 16000);
	    	   ip=localIP;
	       }
	       RemoteTrackerInfo remote= (RemoteTrackerInfo) RPC.waitForProxy(RemoteTrackerInfo.class, RemoteTrackerInfo.versionID, addr, con);
	       TrackerInfo tempInfo=remote.getTrackerInfo();	     
		   details.coreCount=tempInfo.coreCount;
		   details.totalMem=tempInfo.memorySize;
		   //details.
		   details.gflops=0;
		   DatanodeDescriptor datanodeDescriptor=findDNDesc(details.name);
		   
		   try{
			   details.nodeIp=ip;
			   details.location=datanodeDescriptor.getNetworkLocation();			   
		   }
		   catch(Exception e){
			   e.printStackTrace();
		   }
		   detailLocal=details;
		 }
		catch (Throwable e) {
		    e.printStackTrace();
		    System.err.println("exception: " + e);
	
		}
		return details;
	}

	@Override
	public NodeMonitorInfo getMonitorInfo(String name) {
		Random rand=new Random();
		NodeMonitorInfo node=new NodeMonitorInfo();
		TrackerSystemStats info=null;
		try{			
		    TrackerSystemStats tempInfo=HadoopUtils.allLiveNodes.get(name);
		    node.cpu=(tempInfo.currentCPUUsage*100)/6;
		    node.memory=tempInfo.currentMemory;
		 }
		catch (Throwable e) {
		    e.printStackTrace();
		 }
		DecimalFormat formatter=new DecimalFormat("#0.00");
		node.network=rand.nextFloat()*15;
		node.cputemp=23;
		return node;
	}

	@Override
	public Float diskUsageNode(String ip) {
		DatanodeDescriptor desc=findDNDesc(ip);
		return (desc!=null)?desc.getDfsUsedPercent():0;
	}
	
	DatanodeDescriptor findDNDesc(final String ip){
		List<DatanodeDescriptor> liveNodes=HadoopUtils.datanaodesLive;
		
		return (DatanodeDescriptor) CollectionUtils.find(liveNodes, new Predicate() {
			
			@Override
			public boolean evaluate(Object arg0) {				
				return ((DatanodeDescriptor)arg0).getHostName().equals(ip);
			}
		});
		
	}
}
